var express = require('express');
var router = express.Router();


var multiparty = require('multiparty');
var sd = require('silly-datetime');

var DB=require('../../model/db');
var ObjectID=DB.ObjectID;

var async = require('async');

var Host = "";

router.use(function (req, res, next) {
  Host = "http://" + req.headers.host;
  next();
})



/* GET users listing. */
router.get('/', function(req, res, next) {

    //res.send('新闻首页')
    var page = req.query.page || 1;
    var pageSize = 2;

    async.parallel({

        count:function(calback){

            DB.count('article',{},function(err,number){

                calback(err,number)
            })
        },

        article:function(callback){

            DB.find('article',{},{pageSize:pageSize,page:page},function(err,data){

                callback(err,data);
            })
        }
    },function(error,data){

        console.log(data);
        res.render("admin/article/index",{
            host: Host,
            totalPage:Math.ceil(data.count / pageSize) ,
            page:page,
            list: data.article,
        })
    })



});

router.get('/edit', function(req, res, next) {

    var id = req.query.id;
    DB.find('article',{'_id':new ObjectID(id)},function(err,data){
        if(err){
            console.log(err);
            return;
        }
       // console.log(data);
        res.render("admin/article/edit",{
            host:Host,
            list:data[0]
        })
    })
});
router.post('/doEdit', function(req, res, next) {


    var form = new multiparty.Form();
    form.uploadDir = "./public/resource";
    form.parse(req, function(err, fields, files) {

        // console.log(fields);
        // console.log(files);
        var id = fields.id[0];
       // console.log(id);
        var title = fields.title[0];
        var author = fields.author[0];
        var description = fields.description[0];
        var content = fields.content[0];
        var add_time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
        var img = files.img[0].path;
        console.log(files.img[0]);
        var originalFilename = files.img[0].originalFilename;
        if(originalFilename){
            console.log(1)
            var setData={
                title:title,
                author:author,
                description:description,
                content:content,
                add_time:add_time,
                img:img
            }
        }else{
            console.log(2)
            var setData={
                title:title,
                author:author,
                description:description,
                content:content,
                add_time:add_time
            }
        }
        DB.updateOne('article',{'_id':new ObjectID(id)},setData,function(err,data){

         if(err){

         console.log(err);
         return;
         }
         //console.log(data);
            res.send('<script>alert("修改成功");location.href="/admin/article"</script>');
         })

    });

});
router.get('/add', function(req, res, next) {


    res.render("admin/article/add",{
        host:Host
    })
});




router.post('/doAdd', function(req, res, next) {


    var form = new multiparty.Form();
    form.uploadDir = "./public/resource";
    form.parse(req, function(err, fields, files) {

       // console.log(fields);
       // console.log(files);
        var title = fields.title[0];
        var author = fields.author[0];
        var description = fields.description[0];
        var content = fields.content[0];
        var add_time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
        var img = files.img[0].path;

        DB.insertOne('article',{title:title,author:author,description:description,content:content,add_time:add_time,img:img},function(err,data){

            if(err){

                console.log(err);
                return;
            }
            //console.log(data);
            res.send('<script>alert("增加成功");location.href="/admin/article"</script>');
        })

    });

});

router.post("/upload",function(req,res){
    var form = new multiparty.Form();
    form.uploadDir = "./public/resource";
    form.parse(req, function(err, fields, files) {
        var path=files.filedata[0].path;
        res.json({"err":"","msg":path})
    });
});

router.get('/delete', function(req, res, next) {

    var id = req.query.id;
    DB.deleteMany('article',{'_id':new ObjectID(id)},function(err,data){

        if(err){
            console.log(err);
            return;
        }
        res.send('<script>alert("删除成功");location.href="/admin/article"</script>');
    })


});

module.exports = router;